package org.example.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.example.pojo.IhrStaff;
import org.example.service.IhrStaffService;
import org.example.mapper.IhrStaffMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* @author chenhongkai
* @description 针对表【ihr_staff】的数据库操作Service实现
* @createDate 2025-10-20 16:40:34
*/
@Service
public class IhrStaffServiceImpl extends ServiceImpl<IhrStaffMapper, IhrStaff>
    implements IhrStaffService{

    @Autowired
    private IhrStaffMapper ihrStaffMapper;

    @Override
    public Integer syncIhrStaffs(String token) throws JsonProcessingException, ParseException {
        AUTH_TOKEN = token;
        int page = 0;
        while(true){
            Integer result = getStaffByStatus("IN_SERVICE", page);
            if(result == 0){
                break;
            }else{
                page++;
            }
            System.out.println("result= " + result);
        }
        page = 0;
        while(true){
            Integer result = getStaffByStatus("QUIT", page);
            if(result == 0){
                break;
            }else{
                page++;
            }
        }

        return 1;
    }

    private static final String API_URL = "https://openapi.ihr360.com/openapi/thirdparty/api/staff/v1/staffs/basic/status";
    private static String AUTH_TOKEN = "";

    /**
     * 发送POST请求获取员工状态信息
     * @param staffStatus 员工状态
     * @param pageNo 页码
     * @return API响应结果
     */
    public Integer getStaffByStatus(String staffStatus, Integer pageNo) throws JsonProcessingException, ParseException {
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setContentType(MediaType.valueOf("application/json; charset=UTF-8"));
        headers.setBearerAuth(AUTH_TOKEN);

        // 设置请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("staffStatus", staffStatus);
        requestBody.put("pageNo", pageNo);

        // 创建HTTP实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<String> response = restTemplate.postForEntity(API_URL, requestEntity, String.class);

        // 解析返回的JSON数据
        String responseBody = response.getBody();
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(responseBody);

        // 提取dataList数组
        JsonNode dataListNode = rootNode.path("data").path("dataList");

        // 如果需要进一步处理dataList中的数据
        if (dataListNode.isArray()) {
            for (JsonNode staffNode : dataListNode) {
                IhrStaff staff = new IhrStaff();

                // 基本信息映射
                staff.setStaffid(staffNode.path("staffId").asText());
                staff.setStaffno(staffNode.path("staffNo").asText());
                staff.setStaffname(staffNode.path("staffName").asText());
                staff.setEnglishname(staffNode.path("englishName").asText());
                staff.setNickname(staffNode.path("nickName").asText());
                staff.setMobileno(staffNode.path("mobileNo").asText());
                staff.setEmail(staffNode.path("email").asText());
                staff.setWorkemail(staffNode.path("workEmail").asText());
                staff.setWorkphone(staffNode.path("workPhone").asText());
                staff.setStaffstatus(staffNode.path("staffStatus").asText());
                staff.setIdcardtype(staffNode.path("idCardType").asText());
                staff.setIdcardno(staffNode.path("idCardNo").asText());

                // 部门和职位信息
                if (!staffNode.path("departmentId").isNull()) {
                    staff.setDepartmentid(staffNode.path("departmentId").asLong());
                }
                staff.setDepartmentname(staffNode.path("departmentName").asText());
                staff.setPositionid(staffNode.path("positionId").asText());
                staff.setPositionname(staffNode.path("positionName").asText());

                // 个人基本信息
                staff.setSex(staffNode.path("sex").asText());
                staff.setStaffimageid(staffNode.path("staffImageId").asText());
                staff.setStafftype(staffNode.path("staffType").asText());
                staff.setMarrystatus(staffNode.path("marryStatus").asText());
                staff.setHighesteducation(staffNode.path("highestEducation").asText());
                staff.setWorkplace(staffNode.path("workPlace").asText());

                // 日期字段处理

                // 使用改进的日期处理
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                // 只有当字段不为空时才进行解析和设置
                if (!staffNode.path("birthday").isNull() && !staffNode.path("birthday").asText().isEmpty()) {
                    staff.setBirthday(parseDate(staffNode.path("birthday").asText(), sdf));
                }
                if (!staffNode.path("contractBeginDate").isNull() && !staffNode.path("contractBeginDate").asText().isEmpty()) {
                    staff.setContractbegindate(parseDate(staffNode.path("contractBeginDate").asText(), sdf));
                }
                if (!staffNode.path("contractEndDate").isNull() && !staffNode.path("contractEndDate").asText().isEmpty()) {
                    staff.setContractenddate(parseDate(staffNode.path("contractEndDate").asText(), sdf));
                }
                if (!staffNode.path("enrollInDate").isNull() && !staffNode.path("enrollInDate").asText().isEmpty()) {
                    staff.setEnrollindate(parseDate(staffNode.path("enrollInDate").asText(), sdf));
                }
                if (!staffNode.path("leaveDate").isNull() && !staffNode.path("leaveDate").asText().isEmpty()) {
                    staff.setLeavedate(parseDate(staffNode.path("leaveDate").asText(), sdf));
                }
                if (!staffNode.path("probationEndDate").isNull() && !staffNode.path("probationEndDate").asText().isEmpty()) {
                    staff.setProbationenddate(parseDate(staffNode.path("probationEndDate").asText(), sdf));
                }
                if (!staffNode.path("createdDate").isNull() && !staffNode.path("createdDate").asText().isEmpty()) {
                    staff.setCreateddate(parseDate(staffNode.path("createdDate").asText(), dateTimeFormat));
                }
                if (!staffNode.path("lastUpdateDate").isNull() && !staffNode.path("lastUpdateDate").asText().isEmpty()) {
                    staff.setLastupdatedate(parseDate(staffNode.path("lastUpdateDate").asText(), dateTimeFormat));
                }

                // 使用
                this.saveOrUpdate(staff);
            }
        }

        return dataListNode.isEmpty() ? 0 : dataListNode.size();
    }

    // 在 getStaffByStatus 方法中改进日期处理
    private Date parseDate(String dateStr, SimpleDateFormat format) {
        if (dateStr == null || dateStr.isEmpty()) {
            return null;
        }
        try {
            return format.parse(dateStr);
        } catch (ParseException e) {
            System.err.println("日期解析失败: " + dateStr + ", " + e.getMessage());
            return null;
        }
    }

}




